<template>
  <!-- aa -->
  <div>
    <el-scrollbar :height="textHeight" ref="textScrollbarRef" v-loading="loading">
      <div
        v-html="content"
        id="dataForm"
        @contextmenu.prevent="openMenu($event)"
        @click="tdColor($event)"
        @dblclick="trColor($event)"
      ></div>
    </el-scrollbar>
    <!-- </el-card> -->
    <ul
      v-show="visible"
      :style="{ left: left + 'px', top: top + 'px' }"
      class="rightContextmenu"
    >
      <li @click="addTr(contextmenuVal)" v-if="showTr(contextmenuVal)">
        <Plus style="width: 1em; height: 1em" /> 增加行
      </li>
      <li
        @click="delTr(contextmenuVal)"
        v-if="showTr(contextmenuVal)"
        :style="'cursor:' + cursorStyle"
      >
        <Minus style="width: 1em; height: 1em" /> 删除行
      </li>
      <li @click="downWrite(contextmenuVal)" v-if="showDown(contextmenuVal)">
        <Bottom style="width: 1em; height: 1em" /> 向下填充
      </li>
      <li
        v-for="item in childComponentList"
        @click="byConditionDownWrite(contextmenuVal, item.componentId)"
        v-if="showDown(contextmenuVal)"
      >
        <Bottom style="width: 1em; height: 1em" /> 根据{{ item.componentName }}向下填充
      </li>
    </ul>
    <el-button
      @click="upClick"
      style="position: absolute; bottom: 40px; right: 40px; z-index: 9999"
      type="success"
      link
    >
    </el-button>
    <uploadImage ref="imageRef" @showImage="showImage"></uploadImage>
  </div>
</template>

<script setup>
import { queryDataRel } from "@/api/lab/labMethod";
import { postContent, getMarkList, delContent } from "@/api/cyCheck/filling";
import { getRealValue, getFormulaResult, getDecimalLength } from "@/utils/formula";
import { handleSubAndSup } from "@/utils/lims";
import {
  getTemplateData,
  addTableData,
  returnWriteData,
  reloadTable,
  updateFormSign,
} from "@/api/myTask/myTask";
import { listFormula } from "@/api/lab/labMethod";
import bus from "@/utils/eventBus";
import "jquery-ui-dist/jquery-ui";
import "jquery-ui-dist/jquery-ui.min.css";
import "@/components//popover/jquery.webui-popover.min.js";
import "@/components/popover/jquery.webui-popover.min.css";
import "@/components/datepicker/datepicker.css?t=1";
import "@/plugins/jquery.jqprint-0.3.js";
import "@/components/datepicker/moment.min.js";
import "@/components/datepicker/datepicker.all.js";

import { nextTick } from "vue";
import uploadImage from "./uploadImage.vue";

const { proxy } = getCurrentInstance();
const imageRef = ref();
const content = ref("");
const tFId = ref("");
const tableId = ref();
const loading = ref(false);
//用户状态 0：待办 1已办
const userStatus = ref(1);
//步骤id
const userStepId = ref(0);
const cursorStyle = ref("pointer");
const formulaList = ref([]);
const emits = defineEmits(["returnFormulaList", "returnEventResultBtn"]);
let isWrite = false,
  myId,
  $form;
let templateTr; //模板行，自由填报增加行时会用到。

const props = defineProps({
  tFId: {
    type: String, //参数类型
  },
  params: {
    type: Object,
  },
  isFormList: {
    type: Boolean,
    default: false,
  },
});
nextTick(() => {
  tFId.value = props.tFId;
  userStatus.value = props.params.userStatus;
  userStepId.value = props.params.userStepId;
  myId = props.params.myId;
  isWrite = userStatus.value == 0 && userStepId.value == 0;
  tableId.value = props.params.tableId;
  showTable();
  getFormulaList();
  setTimeout(() => {
    addBus();
  }, 300);
});

function addBus() {
  //保存数据
  bus.off("saveData");
  bus.on("saveData", (isAutoSave) => {
    debugger;
    //来源于空的仪器列表保存只需要刷新原始记录（showTable）即可目的是添加了仪器后又删除了需要同步删除原始记录中的仪器信息。
    if(typeof isAutoSave == 'string' && isAutoSave == 'empty_instrument'){
      showTable();
      return;
    }
    saveData(isAutoSave);
    showTable();
  });

  //获取数据
  bus.off("getData");
  bus.on("getData", (tableData) => {
    let dataValues = getData(tableData.isValidate, tableData.ignore);
    tableData.data = dataValues;
  });

  //重载数据
  bus.off("handleReloadTable");
  bus.on("handleReloadTable", () => {
    handleReloadTable();
  });

  //打印表单
  bus.off("printDateForm");
  bus.on("printDateForm", () => {
    printDateForm();
  });
  //刷新表单
  bus.off("showTable");
  bus.on("showTable", () => {
    showTable();
  });
}

function showTable() {
  if (tFId.value) {
    loading.value = true;
    content.value = "";
    nextTick(() => {
      const params = { tFId: tFId.value, userStatus: userStatus.value };
      getTemplateData(params)
        .then((res) => {
            console.log('555',res)
          // content.value = '<table style="border-collapse: collapse; width: 100%;" border="1"><tbody><tr><td style="width: 50.0556%;">测试</td><td style="width: 50.0556%;"><input type="date" style="width: 100%;border:0px"/></td></tr></tbody></table>'
          content.value = res.data.content;
          if (res.data.childComponentList) {
            childComponentList.value = res.data.childComponentList.filter((item) => {
              return item.isUnique == 0 && item.isHide == 0;
            });
          }
          templateTr = res.data.templateTr;
          loading.value = false;
          nextTick(() => {
            $form = $("#dataForm");
            $form.find('td[name="1696048841341812737"]').attr("contenteditable", "false");
            $form.find("td").removeAttr("nowrap");
            loadImage();
            initPopover();
            if (userStatus.value == 0) {
              registerSign();
              $(".datepicker_mm").datePicker({
                format: "YYYY-MM-DD HH:mm",
              });
              $(".datepicker").datePicker({
                format: "YYYY-MM-DD",
              });
              $(".datepicker1").datePicker({
                format: "YYYY年MM月DD日",
              });
              if (props.params && props.params.moduleCode == 13) {
                handleDataRel();
              }
            }
            handleSubAndSup($form, proxy);
            isShowEventResultBtn();
            setFixerTr();
            getHeight();
            addImageEvent();
            if ($("tr.childTr").length == 1) {
              cursorStyle.value = "not-allowed";
            } else {
              cursorStyle.value = "pointer";
            }
          });
        })
        .catch((res) => {
          loading.value = false;
        });
    });
  }
}
function eventResult() {
  if (!isWrite) return;
  if (!tableId.value) return;
  $form = $("#dataForm");
  let $childTrs = $form.find("tr.childTr");
  let flagId = 0; //0:初始化值 1：//继续循环 2://停止循环
  let resultMsg = "";
  //设置只提醒一次
  let msgWarningFlag = { flag: false };
  clearTip();
  if ($childTrs.length == 0) {
    for (let formula of formulaList.value) {
      let resultData = handleFormulaResult($form, formula, msgWarningFlag);
      flagId = resultData.flagId;
      if (resultData.msgWarning && !msgWarningFlag.flag) {
        if (resultMsg.length > 0) {
          resultMsg += "\n";
        }
        resultMsg += resultData.msgWarning;
      }
      if (flagId == 2) break;
    }
  } else {
    $childTrs.each(function () {
      flagId = 0;
      for (let formula of formulaList.value) {
        let resultData = handleFormulaResult($(this), formula, msgWarningFlag);
        if (resultData.msgWarning && !msgWarningFlag.flag) {
          //只需要提示一次。
          if (resultMsg.length > 0) {
            resultMsg += "\n";
          }
          resultMsg += resultData.msgWarning;
          msgWarningFlag.flag = true;
        }
        flagId = resultData.flagId;
        if (flagId == 2) break;
      }
    });
  }
  if (resultMsg.length > 0) {
    proxy.$modal.msgWarning("无法计算结果：" + resultMsg);
  }
  eventMergeSampleResult($childTrs);
  clearTip(5000);
}

function handleFormulaResult($tr, formula, msgWarningFlag) {
  let resultData = { flagId: 0 }; //0:初始化值 1：//继续循环 2://停止循环
  var $resultComponent = $tr.find("td[name='" + formula.resultId + "']");
  if ($resultComponent.length == 0) {
    $resultComponent = $form.find("td[name='" + formula.resultId + "']");
    if ($resultComponent.length == 0 && !msgWarningFlag.flag) {
      proxy.$modal.msgError(
        "未找到结果控件：" + formula.formulaExpressDisplay.split("=")[0]
      );
      resultData.flagId = 2;
      msgWarningFlag.flag = true;
      return resultData;
    } else {
      if ($resultComponent.length > 1) return {};
      if ($(this).parent().hasClass("childWrite")) return {};
    }
  }
  let resultRowspan = $resultComponent.attr("rowspan");
  //公式条件，不同的条件使用对应的公式，例如:平行样相对偏差和绝对偏差这2个条件的公式就不同。
  let condtion = formula.formulaCondition;
  if (condtion) {
    condtion = condtion.replace("=", "==");
    let conditionId = proxy.getCondtion(condtion);
    const $condition = $form.find("select[name='" + conditionId + "']");
    let conditionValue = $condition.val();
    let conditionText = $condition.find("option:selected").text();
    if (!eval(condtion.replace("φ" + conditionId + "φ", conditionValue)) && !eval(condtion.replace("φ" + conditionId + "φ", "'" + conditionText + "'"))) {
      resultData.flagId = 1;
      return resultData;
    }
  }
  //公式：(φ1696729558972825601φ-φ1696729522671124481φ-φ1697869125480968194φ)/(φ1697869039577427969φ*φ1696045595638382594φ*1000)*100
  //应对的表示：样品浓度=(样品A-空白A0-标曲参数b)/(标曲参数a*取样量*1000)*100
  let express = formula.formulaExpress;
  //公式参数：例如上面的样品A（φ1696729558972825601φ），空白A0（1696729522671124481）等。
  let params = formula.paramList;
  for (let param of params) {
    let paramId = param.componentId;
    // if (paramId == formula.resultId) continue; //当前控件为结果控件。
    let value = "";
    if (param.params && param.params.value) {
      value = param.params.value;
      if (value == "" && !msgWarningFlag.flag) {
        proxy.$modal.msgError("引用参数:" + param.paramName + "不能为空！");
        resultData.flagId = 2;
        msgWarningFlag.flag = true;
        break;
      }
      express = express.replace(eval("/φ" + paramId + "φ/g"), value);
      param.value = value;
      continue;
    }
    let $value = $tr.find("td[name='" + paramId + "']");
    if ($value.length == 0) {
      //先查询对应的数据行，数据行中未查到就去主表区域查找。
      $value = $form.find("td[name='" + paramId + "']");
    }
    if ($value.length == 0 && !msgWarningFlag.flag) {
      proxy.$modal.msgError("未从公式中查找到参数：" + param.paramName);
      resultData.flagId = 2;
      $value.addClass("tipError");
      msgWarningFlag.flag = true;
      break;
    }
    value = getRealValue($resultComponent, $value.text());
    if (value == -1000 || value == -1100) {
      //变量为低于检出限时，结果也为检出限。
      resultData.flagId = 1;
      if (value == -1000) {
        $resultComponent.html($value.text());
      } else {
        $resultComponent.html($resultComponent.data("resultValue"));
      }
      $resultComponent.addClass("tipInfo");
      setIsHg($resultComponent, $value.text());
      break;
    } else if (value == -2000) {
      if ($.trim($value.text()).length == 0 && !msgWarningFlag.flag) {
        proxy.$modal.msgError("公式计算:" + param.paramName + "不能为空！");
        $value.addClass("tipError");
        msgWarningFlag.flag = true;
      } else if (!msgWarningFlag.flag) {
        proxy.$modal.msgError("非法数据：" + param.paramName + "-" + $value.text());
        $value.addClass("tipError");
        msgWarningFlag.flag = true;
      }
      resultData.flagId = 2;
      break;
    } else if (value == -3000) {
      resultData.flagId = 1;
      break;
    } else if (typeof value != "number" && value == "" && !msgWarningFlag.flag) {
      proxy.$modal.msgError("公式计算:" + param.paramName + "不能为空！");
      $value.addClass("tipError");
      msgWarningFlag.flag = true;
      resultData.flagId = 2;
      break;
    }
    express = express.replace(eval("/φ" + paramId + "φ/g"), value);
    param.value = value;
    //求平均值
    if (resultRowspan > 1 && params.length == 1) {
      let $nextTr = $tr.next();
      let count = 1;
      for (let t = 2; t <= resultRowspan; t++) {
        $value = $nextTr.find("td[name='" + paramId + "']");
        value = getRealValue($resultComponent, $value.text());
        if (value == "") {
          continue;
        } else if (value == -1000 || value == -1100) {
          //变量为低于检出限时，结果也为检出限。
          resultData.flagId = 1;
          if (value == -1000) {
            $resultComponent.html($value.text());
          } else {
            $resultComponent.html($resultComponent.data("resultValue"));
          }
          $resultComponent.addClass("tipInfo");
          setIsHg($resultComponent, $value.text());
          break;
        } else if (value == -2000) {
          if ($.trim($value.text()).length == 0 && !msgWarningFlag.flag) {
            proxy.$modal.msgError("公式计算:" + param.paramName + "不能为空！");
            $value.addClass("tipError");
            msgWarningFlag.flag = true;
          } else if (!msgWarningFlag.flag) {
            proxy.$modal.msgError("非法数据：" + param.paramName + "-" + $value.text());
            $value.addClass("tipError");
            msgWarningFlag.flag = true;
          }
          resultData.flagId = 2;
          break;
        } else if (value == -3000) {
          continue;
        }
        express += "+" + value;
        count++;
      }
      express = "(" + express + ")/" + count;
    }
  }
  if (resultData.flagId == 1 || resultData.flagId == 2) {
    return resultData;
  }
  let resultValue;
  try {
    resultValue = getFormulaResult($resultComponent, formula, express);
  } catch (e) {
    resultData.msgWarning = e.message;
  }
  if (resultValue == "" && !resultData.msgWarning) {
    resultData.msgWarning = express;
  }

  if (typeof resultValue == "object") {
    resultValue = resultValue["resultValue"];
  }
  $resultComponent.addClass("tipInfo");
  $resultComponent.html(resultValue);
  if ($resultComponent && $resultComponent.data("blur")) {
    //可能有的公式计算的结果做为其它自动计算的变量，例如：标曲表的标曲空白值=当前标曲空白值-第一个空白值。
    $resultComponent.blur();
  }
  return resultData;
}
/**
 * 计算合并后的样品结果值。
 */
function eventMergeSampleResult($childTrs) {
  $childTrs.each(function () {
    const $tr = $(this);
    const sampleType = $tr.attr("sampletype");
    if (!sampleType || sampleType != 50) {
      //50:合并的样品
      return true;
    }
    const $resultValues = $tr.find("td.isRowavg");
    if ($resultValues.length == 0) {
      return false;
    }
    // let splitTrs = $tr.prevAll("tr[sampletype=51]").siblings();
    let $splitTrs = [];
    let $splitTr = $tr.prev();
    while (true) {
      if ($splitTr.attr("sampletype") != 51) {
        break;
      }
      $splitTrs.push($splitTr);
      $splitTr = $splitTr.prev();
    }
    if ($splitTrs.length == 0) {
      proxy.$modal.msgError("未找到拆分的样品");
    }
    $resultValues.each(function () {
      const $resultComponent = $(this);
      $resultComponent.html("");
      const resultName = $resultComponent.attr("name");
      let express = "";
      let firstValue;
      for (let i in $splitTrs) {
        const $splitResult = $splitTrs[i].find("td[name='" + resultName + "']");
        const splitResultValue = getRealValue($splitResult, $splitResult.text());
        if (splitResultValue == -1000 || splitResultValue == -1100) {
          //变量为低于检出限时，结果也为检出限。
          if (splitResultValue == -1000) {
            $resultComponent.html($splitResult.text());
          } else {
            $resultComponent.html($splitResult.data("resultValue"));
          }
          $resultComponent.addClass("tipInfo");
          return true;
        } else if (splitResultValue == -2000) {
          return true;
        } else if (splitResultValue == -3000) {
          $resultComponent.html("/");
          $resultComponent.addClass("tipInfo");
          return true;
        }
        if (!firstValue) {
          firstValue = splitResultValue;
        }
        express += "+" + splitResultValue;
      }
      if (express.length == 0) return true;
      express = express.substring(1);
      express = "(" + express + ")/" + $splitTrs.length;
      const formula = {
        isResult: 1,
        paramList: [{ value: firstValue }],
        ruleList: [{ruleConditionId:7,ruleTypeId:1,xyId:1}]
      };
      let resultValue;
      try {
        resultValue = getFormulaResult($resultComponent, formula, express);
      } catch (e) {}
      if (typeof resultValue == "object") {
        resultValue = resultValue["resultValue"];
      }
      $resultComponent.addClass("tipInfo");
      $resultComponent.html(resultValue);
    });
  });
}
function clearTip(timeOut) {
  if (!timeOut) {
    $form.find(".tipError").removeClass("tipError");
    $form.find(".tipInfo").removeClass("tipInfo");
    return;
  }
  setTimeout(() => {
    $form.find(".tipError").removeClass("tipError");
    $form.find(".tipInfo").removeClass("tipInfo");
  }, timeOut);
}
function registerSign() {
  let signData = { tFId: tFId.value };
  $(".signBtn").on("click", function () {
    let $signImage = $(this).parent().find("img.sign");
    if ($signImage.length == 0) return;
    let name = $signImage.attr("name");
    let imageData = $signImage.attr("src");
    if (!imageData) return;
    signData.signId = name;
    signData.signStr = imageData;
    updateFormSign(signData).then((res) => {});
  });
}
function addImageEvent() {
  // if(userStatus.value != 0 && userStepId.value != 0) return;
  //delegate：委托事件，也可以对以后新创建的dom生效。
  $form.delegate("td.component.image", "click", function () {
    let imageType = $(this).data("filetype");
    if (!imageType) {
      proxy.$modal.msgError("未指定图片类型，请联系管理员！");
      return;
    }
    let bytes = $(this).find(".img-lg").attr("src");
    imageRef.value.editCropper(
      tFId.value,
      imageType,
      $(this).data("imageid"),
      bytes,
      $(this)
    );
  });
}

/**
 * 回显图片
 * @param {图片数据} imageData
 */
function showImage(imageData, $imageConent) {
  let { id, bytes } = imageData;
  let imageHtml = '<img src="' + bytes + '" class="img-lg img-lg" />';
  $imageConent.find(".img-lg").remove();
  $imageConent.data("imageid", id);
  $imageConent.prepend(imageHtml);
}

function loadImage() {
  $form.find("td.image").each(function () {
    if (!$(this).data("imageid")) return true;
    let $that = $(this);
    proxy.$download.previewPicById($that.data("imageid")).then((res) => {
      $that.find(".img-lg").remove();
      let imageHtml =
        '<img src="' + res + '" class="img-lg"  style="width:100px;height:200px;"/>';
      $that.prepend(imageHtml);
    });
  });
}
//设置固定行为表头或表尾
function setFixerTr() {
  let $fixedHead = $("tr.fixed-head");
  let height = 0;
  $fixedHead.each(function (i) {
    $(this).css("top", height + "px");
    height += $(this).height();
  });
  let $fixedFoot = $("tr.fixed-foot");
  height = 0;
  for (let i = $fixedFoot.length - 1; i >= 0; i--) {
    let $this = $fixedFoot.eq(i);
    $this.css("bottom", height + "px");
    height += $this.height() + 1;
  }
}
function getData(isValidate, ignore) {
  if (!tableId.value) return;
  let jsonData = {};
  if (isValidate) {
    clearTip();
  }
  let warningMsg = "";
  $form.find(".component").each(function () {
    if (!$(this).parents("tr:first").hasClass("childTr")) {
      //排除子表行控件
      let jsonValue = getComponentData($(this), isValidate, ignore);
      if (typeof jsonValue == "string" && jsonValue.startsWith("warning")) {
        if (warningMsg.indexOf(jsonValue.substring(7)) == -1) {
          warningMsg += "," + jsonValue.substring(7);
        }
        return true;
      }
      if (isValidate && typeof jsonValue === "boolean") {
        jsonData = jsonValue;
        return false;
      }
      if (jsonValue) {
        Object.assign(jsonData, jsonValue);
      }
    }
  });
  if (isValidate && typeof jsonData === "boolean" && !jsonData) {
    return jsonData;
  }
  //查询子表的控件数据
  let childJsonArray = [];
  $form.find("tr.childTr").each(function (i) {
    let childJson = { orderNum: i + 1 };
    let $components = $(this).find(".component");
    $components.each(function () {
      let jsonValue = getComponentData($(this), isValidate, ignore);
      if (typeof jsonValue == "string" && jsonValue.startsWith("warning")) {
        if (warningMsg.indexOf(jsonValue.substring(7)) == -1) {
          warningMsg += "," + jsonValue.substring(7);
        }
        return true;
      }
      if (jsonValue) {
        Object.assign(childJson, jsonValue);
      }
      if ($(this).hasClass("addJcxm") && $(this).data("jcxm_id")) {
        const jcxmIds = $(this).data("jcxm_id").split(",");
        jcxmIds.forEach((jcxmId) => {
          childJson[jcxmId] = $(this).attr("name");
        });
      }
    });
    if ($.isEmptyObject(childJson)) return true;
    if ($(this).attr("id")) {
      childJson.id = $(this).attr("id");
    }
    if ($(this).data("id")) {
      Object.assign(childJson, $(this).data("id"));
    }
    if (!jsonData.childWrite && $(this).hasClass("child-write")) {
      //child-write：自由填写标识
      jsonData.childWrite = true;
    }
    if ($(this).attr("name") == "1696048841341812737") {
      //防止人为修改检出限数据。
      delete childJson[$(this).attr("name")];
      const checkDataList = $(this).data("checkData");
      // const checkLimitValue = getCheckLimitDataByTr($(this));
      if (checkDataList) {
        const checkLimitValue = checkDataList[0];
        childJson[$(this).attr("name")] = checkLimitValue.orgCheckLimit;
        if (checkLimitValue.checkLimitUnit) {
          childJson["checkLimitUnit"] = checkLimitValue.checkLimitUnit;
        }
      }
    }
    if (!$.isEmptyObject(childJson) && $components.length > 0) {
      //判断json对象是否为空
      childJsonArray.push(childJson);
    }
  });
  if (isValidate) {
    clearTip(10000);
  }
  if (warningMsg.length > 0) {
    return "warning" + warningMsg.substring(1);
  }
  if (childJsonArray.length > 0) {
    jsonData.childDataList = childJsonArray;
  }
  jsonData.tFId = tFId.value;
  jsonData.myId = myId;
  return jsonData;
}
/**
 * 保存数据
 */
function saveData(isAuthSave) {
  let jsonData = getData();
  //保存数据
  addTableData(jsonData).then((res) => {
    if (!isAuthSave) {
      proxy.$modal.msgSuccess("保存成功！");
    }
    showTable();
  });
}
function getFormulaList() {
  if (!isWrite) return;
  formulaList.value = [];
  listFormula(props.params).then((res) => {
    if (res.data) {
      formulaList.value = res.data;
    }
    emits("returnFormulaList", formulaList.value);
  });
}

function isShowEventResultBtn() {
  emits("returnEventResultBtn", $form.find("td.isRowavg:first").length > 0);
}

function returnWrite() {
  proxy.$modal.confirm("确认要退回给填报员吗？").then(function () {
    let jsonData = {};
    if (tableId.value) {
      jsonData = getData();
    }
    if (myId) {
      jsonData.myId = myId;
    }
    returnWriteData(jsonData).then((res) => {
      proxy.$modal.msgSuccess("提交成功！");
      try {
        bus.emit("closeDialog");
      } catch (e) {
        showTable();
      }
    });
  });
}

/**
 * 重新加载模板
 */
function handleReloadTable() {
  if (!tFId.value) {
    proxy.$modal.msgError("未找到表单id！");
    return false;
  }
  proxy.$modal.confirm("确定要重载数据吗？").then(function () {
    reloadTable(tFId.value).then((res) => {
      showTable(res.data);
    });
  });
}
function getComponentData($that, isValidate, ignore) {
  let name = $that.attr("name");
  if (!name) return null;
  let json = {};
  let jsonValue = "";
  let $componentName = $that.find("[name=" + name + "]");
  if ($componentName.length == 0) {
    $componentName = $that.find("[data-id='" + name + "']");
  }
  if ($componentName.length == 0) {
    if ($that.hasClass("image")) {
      jsonValue = $that.data("imageid");
    } else if ($that.val().length > 0) {
      jsonValue = $.trim($that.val());
    } else {
      if ($that.data("v-value")) {
        jsonValue = $.trim($that.data("v-value"));
      } else {
        if ($that.data("type")) {//长文本
          jsonValue = $.trim($that.html());
        } else {
          jsonValue = $.trim($that.text());
        }
      }
    }
    if (!ignore && isValidate) {
      if ($that.data("required") == 1 && $.trim(jsonValue).length == 0) {
        $that.addClass("tipError");
        return "warning1" + $that.attr("label") + "不能为空！";
      } else if (jsonValue.length > 0 && $that.data("pointcount")) {
        if (/^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(jsonValue)) {
          const pointCount = parseInt($that.data("pointcount"));
          if (getDecimalLength(jsonValue) != pointCount) {
            $that.addClass("tipError");
            return "warning2" + $that.attr("label") + "应该保留" + pointCount + "位小数";
          }
        }
      }
    }
  } else {
    let nodeType = $componentName[0].nodeName;
    let type = $componentName.attr("type");
    if (nodeType && nodeType.toLowerCase() == "select") {
      jsonValue = $componentName.val();
      json[name + "t"] = $componentName.find("option:selected").text();
    } else if (type && (type == "checkbox" || type == "radio")) {
      let $checkbox = $that.find("input[data-id='" + name + "']:checked");
      if ($checkbox.length == 0) return null;
      let values = "";
      let texts = "";
      $checkbox.each(function () {
        values += "," + this.value;
        texts += "、" + $(this).next().text();
      });
      jsonValue = values.substring(1);
      json[name + "t"] = texts.substring(1);
    } else if ($componentName.hasClass("sign")) {
      //签字控件并且显示
      if ($componentName.is(":visible")) {
        jsonValue = $componentName.attr("src");
      } else if (isValidate) {
        proxy.$modal.msgError($componentName.attr("label") + "不能为空！");
        return false;
      }
    } else {
      jsonValue = $.trim($componentName.val());
    }
  }
  //if (jsonValue.length == 0) return null;
  json[name] = jsonValue;
  return json;
}
/**
 * 数据引用
 */
function handleDataRel() {
  queryDataRel(tFId.value).then((res) => {
    if (!res.data) {
      proxy.$modal.msgError("未查询到需要引用的数据！");
      return;
    }
    setRelData(res.data);
  });
}

bus.off("dataRel");
bus.on("dataRel",() => {
  handleDataRel()
})

function setRelData(relDataList) {
  out: for (const i in relDataList) {
    const dataMap = relDataList[i];
    let $componentTr = $form.find("tr[id='" + dataMap.id + "']");
    if ($componentTr.length == 0) {
      proxy.$modal.msgError("将数据渲染到当前表中时未找到对应的位置！");
      break;
    }
    for (const compoentId in dataMap) {
      if (compoentId == "id") continue;
      const $dataComponent = $componentTr.find("td[name='" + compoentId + "']");
      if ($dataComponent.length == 0) {
        proxy.$modal.msgError("将数据渲染到当前表中时未找到对应的位置！");
        break out;
      }
      $dataComponent.html(dataMap[compoentId]);
      $dataComponent.addClass("relData"); //给匹配到的数据添加背景色
    }
  }
  //3秒后自动移除匹配到的数据背景色
  setTimeout(() => {
    $form.find("td.relData").removeClass("relData");
  }, 3000);
}
// ---------------------------------右击列表----------------------------------------
const left = ref(0);
const top = ref(0);
const visible = ref(false);
const contextmenuVal = ref({});
const childComponentList = ref([]);
// 右击事件
function openMenu(e) {
  if (userStatus.value != 0 || userStepId.value != 0) return;
  let $target = $(e.target);
  let isNext = false;
  if (e.target.nodeName.toLowerCase() != "td") {
    $target = $target.parents("td:first");
    isNext = true;
  }
  if (!$target.parents("tr:first").hasClass("childTr")) return;
  if (!isNext && $target.prop("contenteditable") === "false") return;
  // 右击加背景颜色
  var $bgc = $(".bgcTdr");
  $bgc.removeClass("bgcTdr");
  $target.addClass("bgcTdr");
  setPosition(e);
  visible.value = true;
  if (
    e.target.nodeName.toLowerCase() == "td" &&
    e.target.childNodes[0]?.nodeName != "#text" &&
    e.target.childNodes[0]
  ) {
    contextmenuVal.value = e.target.childNodes[0];
    return;
  }

  contextmenuVal.value = e.target;
}

function setPosition(e) {
  const $contextmenu = $(".rightContextmenu");
  const targetWith = $contextmenu.width() || 150;
  const targetHeight = $contextmenu.height() || 77;
  let clientx = e.clientX;
  if (clientx + targetWith >= window.innerWidth) {
    clientx = clientx - targetWith;
  }
  let clienty = e.clientY;
  if (clienty + targetHeight + 100 >= window.innerHeight) {
    clienty = clienty - targetHeight;
  }
  if (props.isFormList) {
    let position = $("#dataFormMainBox" + tFId.value).offset();
    left.value = clientx - position.left;
    top.value = clienty - position.top;
    return;
  }
  left.value = clientx;
  top.value = clienty;
}
function closeMenu() {
  visible.value = false;
}
// 提示框
const markList = ref([]);
function initPopover() {
  var settings = {
    trigger: "dblclick",
    title: "标记详情",
    width: 300,
    closeable: true,
    // 确定  取消  关闭  按钮显示隐藏
    showBtn: userStatus.value == 0,
    style: "",
    padding: false,
    content: function (webuiPopover) {
      var markId = webuiPopover.$element.attr("markId");
      var content = "";
      for (const item of markList.value) {
        if (item.markId == markId) {
          content = item.content;
          break;
        }
      }
      return content;
    },
    onHide: function ($target, $element, btn) {
      return new Promise((resolve, reject) => {
        var markId = $element.attr("markId");
        if (btn == "confirm") {
          var content = $target.find(".webui-popover-content").text();
          var componentId = markId ? "" : $element.attr("name");
          var childFormId = markId ? "" : $element.parent().attr("id");
          if (!content) {
            proxy.$modal.msgError("请输入标记内容");
            return false;
          }
          let temp = {
            content: content,
            componentId: componentId,
            markId: markId,
            childFormId: childFormId,
            tFId: markId ? "" : tFId.value,
          };
          postContent(temp)
            .then((res) => {
              if (!markId) {
                $element.attr("markId", res.data);
                markList.value.push({ markId: res.data, content: content });
              } else {
                for (const item of markList.value) {
                  if (item.markId == markId) {
                    item.content = content;
                    break;
                  }
                }
              }
              $element.addClass("markColor");
              resolve(true);
            })
            .catch(() => {
              reject(false);
            });
        } else {
          if (!markId) {
            proxy.$modal.msgError("没有标记");
            return false;
          }
          delContent(markId)
            .then((res) => {
              proxy.$modal.msgSuccess("删除成功");
              markList.value = markList.value.filter((item) => {
                return item.markId != markId;
              });
              $element.removeAttr("markId");
              $element.removeClass("markColor");
              resolve(true);
            })
            .catch((res) => {
              reject(false);
            });
        }
      });
    },
  };
  // if (userStatus.value === 0) {
  getMarkList({ myId: myId }).then((res) => {
    markList.value = res.data;
    for (const item of markList.value) {
      let $component;
      if (item.childFormId) {
        //子表行
        $component = $("#" + item.childFormId).find("[name='" + item.componentId + "']");
      } else {
        $component = $("[name='" + item.componentId + "']");
      }
      if ($component.length > 0) {
        $component.addClass("markColor").addClass("mark_");
        $component.attr("markId", item.markId);
      }
    }
    if (markList.value.length > 0 || userStepId.value == 1 || userStepId.value == 2) {
      $(".mark_").webuiPopover("destroy").webuiPopover(settings);
    }
  });
  // }
}

// 向下填充
function downWrite(target) {
  let $s = $(target);
  let isChild = target.nodeName.toLowerCase() != "td";
  if (isChild) {
    let value = $s.val();
    let $target = $s.parents("td:first");
    var $tr = $target.parents("tr:first");
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      var $t = $tr.find("[name='" + $target.attr("name") + "']");
      if ($t.length == 0) {
        break;
      }
      if ($t[1].type == "select-one") {
        var $options = $t[1].children;
        for (const index in $options) {
          if ($options[index].getAttribute("value") == value) {
            $options[index].setAttribute("selected", "");
            break;
          } else {
            $options[index].removeAttribute("selected");
          }
        }
      } else {
        var $e = $t[1];
        $e.value = value;
      }
    }
  } else {
    let value = $s.text();
    var $tr = $s.parents("tr:first");
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      let $td = $tr.find("[name='" + $s.attr("name") + "']");
      if ($td.length == 0) {
        break;
      }
      $td.text(value);
    }
  }
}

// 根据条件向下填充
function byConditionDownWrite(target, cId) {
  let $s = $(target);
  let isChild = target.nodeName.toLowerCase() != "td";
  var clickValue = "";
  if (isChild) {
    for (const item of $s.parents("td:first").siblings()) {
      if (item.attributes.name.value == cId) {
        let $i = $(item);
        clickValue = $i.text();
        break;
      }
    }
    let value = $s.val();
    let $target = $s.parents("td:first");
    var $tr = $target.parents("tr:first");
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      var $t = $tr.find("[name='" + $target.attr("name") + "']");
      if ($t.length == 0) {
        break;
      }
      if ($t[1].type == "select-one") {
        var $options = $t[1].children;
        for (const item of $tr[0].children) {
          if (item.attributes.name.value == cId) {
            let $i = $(item);
            if ($i.text() == clickValue) {
              for (const index in $options) {
                if ($options[index].getAttribute("value") == value) {
                  $options[index].setAttribute("selected", "");
                  break;
                } else {
                  $options[index].removeAttribute("selected");
                }
              }
            }
            break;
          }
        }
      } else {
        for (const item of $tr[0].children) {
          if (item.attributes.name.value == cId) {
            let $i = $(item);
            if ($i.text() == clickValue) {
              var $e = $t[1];
              $e.value = value;
            }
            break;
          }
        }
      }
    }
  } else {
    let value = $s.text();
    var $tr = $s.parents("tr:first");
    for (const item of $s.siblings()) {
      if (item.attributes.name.value == cId) {
        let $i = $(item);
        clickValue = $i.text();
        break;
      }
    }
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      let $td = $tr.find("[name='" + $s.attr("name") + "']");
      if ($td.length == 0) {
        break;
      }
      for (const item of $tr[0].children) {
        if (item.attributes.name.value == cId) {
          let $i = $(item);
          if ($i.text() == clickValue) {
            $td.text(value);
          }
          break;
        }
      }
    }
  }
}

// 增加行
function addTr(target) {
  var $target = $(target);
  var $tr = $target.parents("tr:first");
  let $clone = $tr.clone();
  $clone.find(".component").each(function () {
    let $that = $(this);
    let name = $that.attr("name");
    let $componentName = $that.find("[name=" + name + "]");
    if ($componentName.length == 0) {
      $componentName = $that.find("[data-id='" + name + "']");
    }
    if ($componentName.length == 0) {
      if ($that.hasClass("image")) {
        $that.removeData("imageid");
        $that.find(".img-lg").remove();
      } else {
        $that.text("");
      }
    } else {
      if ($componentName.prop("nodeName").toLowerCase() == "input") {
        $componentName.val("");
      }
    }
    cursorStyle.value = "pointer";
  });
  $clone.removeAttr("id");
  $clone.find(".hasDatepicker").removeClass("hasDatepicker").removeAttr("id");
  $tr.after($clone);
  $tr.next().find(".date").datepicker({
    dateFormat: "yy-mm-dd", // 设置日期格式
  });
  $(".datepicker_mm").datePicker({
    format: "YYYY-MM-DD HH:mm",
  });
  $(".datepicker").datePicker({
    format: "YYYY-MM-DD",
  });
  $(".datepicker1").datePicker({
    format: "YYYY年MM月DD日",
  });
}

// 删除行
function delTr(target) {
  if ($("tr.childTr").length == 1) {
    return;
  }
  var $target = $(target);
  var $tr = $target.parents("tr:first");
  $tr.remove();
  if ($("tr.childTr").length == 1) {
    cursorStyle.value = "not-allowed";
  } else {
    cursorStyle.value = "pointer";
  }
}

// 显示隐藏ul中的li
function showDown(e) {
  let $target = $(e);
  if (e.nodeName?.toLowerCase() != "td") {
    $target = $target.parents("td:first");
  }
  if (!$target.attr("sourcetype")) return false;
  let sourcetype = parseInt($target.attr("sourcetype"));
  let isWrite = parseInt($target.attr("isWrite"));
  if (sourcetype != 2 && sourcetype != 3 && isWrite != 1) return false;
  return true;
}

// 显示隐藏ul中的li
function showTr(e) {
  let $target = $(e);
  if (e.nodeName?.toLowerCase() != "td") {
    $target = $target.parents("td:first");
  }
  if (!$target.parents("tr:first").is(".child-write")) return false;
  return true;
}

// 单击td变色
function tdColor(e) {
  var $target = $(e.target);
  var $bgc = $(".bgcTdr");
  $bgc.removeClass("bgcTdr");
  if ($target[0].tagName.toLowerCase() != "td") {
    $target = $target.parents("td:first");
  }
  $target.addClass("bgcTdr");
}

// 双击tr变色
function trColor(e) {
  var $target = $(e.target);
  var $tr = $target.parents("tr:first");
  var $bgc = $(".bgcTdr");
  $bgc.removeClass("bgcTdr");
  $tr.addClass("bgcTdr");
}

watch(visible, (value) => {
  if (value) {
    document.body.addEventListener("click", closeMenu);
  } else {
    document.body.removeEventListener("click", closeMenu);
  }
});

// -------------------------------------------打印---------------------------------------------
function printDateForm() {
  let isPortrait = $("#dataForm").find("table:first").width() * 0.75 > 600;
  $("#dataForm").jqprint({
    debug: false,
    importCSS: false,
    operaSupport: true,
    printContainer: true,
    portrait: isPortrait,
  });
}

// ---------------------------------------------回到顶部--------------------------------------
function upClick() {
  document.getElementById("dataForm").scrollIntoView();
}

const textHeight = ref(0);

function getHeight() {
  nextTick(() => {
    textHeight.value = proxy.getSubFileHeight(proxy, "textScrollbarRef", 40);
  });
}

function isUpClick() {
  // document.getElementById("dataForm")
}
onMounted(() => {
  nextTick(function () {
    getHeight();
    window.addEventListener("resize", getHeight);
    isUpClick();
    window.addEventListener("resize", isUpClick);
  });
});
onUpdated(() => {
  nextTick(() => {
    getHeight();
    isUpClick();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getHeight);
  document.removeEventListener("keydown", handleKeyDown);
  window.addEventListener("resize", isUpClick);
});

function upCommon(tr, td) {
  var foundEditableTd = false;
  var currentTr = tr;

  if (currentTr && !foundEditableTd) {
    var tds = currentTr.querySelectorAll("td");
    for (var i = tds.length - 1; i >= 0; i--) {
      var currentTd = tds[i];
      if (currentTd.getAttribute("contentEditable") == "true") {
        currentTd.focus();
        var $bgc = $(".bgcTdr");
        $bgc.removeClass("bgcTdr");
        currentTd.classList.add("bgcTdr");
        foundEditableTd = true;
        break;
      }
    }
    if (!foundEditableTd) {
      ArrowUp({ target: td ? td : tds[tds.length - 1] });
    }
  }
}

function downCommon(tr, td) {
  var foundEditableTd = false;
  var currentTr = tr;
  if (currentTr && !foundEditableTd) {
    var tds = currentTr.querySelectorAll("td");
    for (var i = 0; i < tds.length; i++) {
      var currentTd = tds[i];
      if (currentTd.getAttribute("contentEditable") == "true") {
        currentTd.focus();
        var $bgc = $(".bgcTdr");
        $bgc.removeClass("bgcTdr");
        currentTd.classList.add("bgcTdr");
        foundEditableTd = true;
        break;
      }
    }
    if (!foundEditableTd) {
      ArrowDown({ target: td ? td : tds[0] });
    }
  }
}

function focusTd(td) {
  td.focus();
  var $bgc = $(".bgcTdr");
  $bgc.removeClass("bgcTdr");
  td.classList.add("bgcTdr");
}

function ArrowUp(e) {
  var tdIndex = Array.from(e.target.parentNode.children).indexOf(e.target);
  var tr = e.target.closest("tr");
  if (tr) {
    var previousTr = tr.previousElementSibling;
    if (previousTr) {
      var td = previousTr.querySelectorAll("td")[tdIndex];
      if (td) {
        if (td.getAttribute("contentEditable") == "true") {
          focusTd(td);
        } else {
          upCommon(previousTr, td);
        }
      } else {
        upCommon(previousTr);
      }
    } else {
      var table = tr.closest("table");
      if (table) {
        var previousTable = table.previousElementSibling;
        if (previousTable) {
          var lastRow = previousTable.querySelector("tbody tr:last-child");
          if (lastRow) {
            var td = lastRow.querySelectorAll("td")[tdIndex];
            if (td) {
              if (td.getAttribute("contentEditable") == "true") {
                focusTd(td);
              } else {
                upCommon(lastRow, td);
              }
            } else {
              upCommon(lastRow);
            }
          }
        }
      }
    }
  }
}

function ArrowDown(e) {
  var tdIndex = Array.from(e.target.parentNode.children).indexOf(e.target);
  var tr = e.target.closest("tr");
  if (tr) {
    var previousTr = tr.nextElementSibling;
    if (previousTr) {
      var td = previousTr.querySelectorAll("td")[tdIndex];
      if (td) {
        if (td.getAttribute("contentEditable") == "true") {
          focusTd(td);
        } else {
          downCommon(previousTr, td);
        }
      } else {
        downCommon(previousTr);
      }
    } else {
      var table = tr.closest("table");
      if (table) {
        var nextTable = table.nextElementSibling;
        if (nextTable) {
          var lastRow = nextTable.querySelector("tbody tr:first-child");
          if (lastRow) {
            var td = lastRow.querySelectorAll("td")[tdIndex];
            if (td) {
              if (td.getAttribute("contentEditable") == "true") {
                focusTd(td);
              } else {
                downCommon(lastRow, td);
              }
            } else {
              downCommon(lastRow);
            }
          }
        }
      }
    }
  }
}

function ArrowLeft(e) {
  var previousTD = e.target.previousElementSibling;
  if (previousTD) {
    if (previousTD.getAttribute("contentEditable") == "true") {
      focusTd(previousTD);
    } else {
      ArrowLeft({ target: previousTD });
    }
  } else {
    var previousTr = e.target.closest("tr").previousElementSibling;
    if (previousTr) {
      var tds = previousTr.querySelectorAll("td");
      var td = tds[tds.length - 1];
      if (td.getAttribute("contentEditable") == "true") {
        focusTd(td);
      } else {
        ArrowLeft({ target: td });
      }
    } else {
      var previousTable = e.target.closest("tr").closest("table").previousElementSibling;
      if (previousTable) {
        var lastRow = previousTable.querySelector("tbody tr:last-child");
        if (lastRow) {
          var tds = lastRow.querySelectorAll("td");
          var td = tds[tds.length - 1];
          if (td.getAttribute("contentEditable") == "true") {
            focusTd(td);
          } else {
            ArrowLeft({ target: td });
          }
        }
      }
    }
  }
}

function ArrowRight(e) {
  var nextTD = e.target.nextElementSibling;
  if (nextTD) {
    if (nextTD.getAttribute("contentEditable") == "true") {
      focusTd(nextTD);
    } else {
      ArrowRight({ target: nextTD });
    }
  } else {
    var previousTr = e.target.closest("tr").nextElementSibling;
    if (previousTr) {
      var tds = previousTr.querySelectorAll("td");
      var td = tds[0];
      if (td.getAttribute("contentEditable") == "true") {
        focusTd(td);
      } else {
        ArrowRight({ target: td });
      }
    } else {
      var nextTable = e.target.closest("tr").closest("table").nextElementSibling;
      if (nextTable) {
        var firstRow = nextTable.querySelector("tbody tr:first-child");
        if (firstRow) {
          var tds = firstRow.querySelectorAll("td");
          var td = tds[0];
          if (td.getAttribute("contentEditable") == "true") {
            focusTd(td);
          } else {
            ArrowRight({ target: td });
          }
        }
      }
    }
  }
}

// 定义事件处理函数
function handleKeyDown(e) {
  if (e.key) {
    var dataForm = document.getElementById("dataForm");
    var event = e.target;
    if (dataForm.contains(event)) {
      if (e.key == "ArrowUp") {
        ArrowUp({ target: event });
      } else if (e.key == "ArrowDown") {
        ArrowDown({ target: event });
      } else if (e.key == "ArrowLeft") {
        ArrowLeft({ target: event });
      } else if (e.key == "ArrowRight") {
        ArrowRight({ target: event });
      }
    }
  }
}
defineExpose({
  eventResult,
});
// 添加事件监听器
document.addEventListener("keydown", handleKeyDown);
</script>

<style lang="scss" scoped>
#dataForm:deep(div.sign:hover .cha) {
  display: block !important;
}

#dataForm:deep(td) {
  word-break: break-all !important;
}

#dataForm:deep(.bgcTdr) {
  background-color: #d8fdde;
}

#dataForm:deep(.fixed-head),
#dataForm:deep(.fixed-foot) {
  position: sticky;
  background-color: #eee;
  z-index:1;
}

.rightContextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);

  li {
    margin: 0;
    padding: 7px 16px;
    cursor: pointer;

    &:hover {
      background: #eee;
    }
  }
}

#dataForm:deep(.markColor) {
  background: transparent url("/src/assets/images/report.gif") no-repeat scroll 0 0;
}

#dataForm:deep(td .cover::after) {
  content: "+";
  position: absolute;
  top: 50%;
  left: 50%;
  color: #999;
  font-size: 35px;
  transform: translate(-50%, -50%);
}

#dataForm:deep(.component.image:hover:after) {
  content: "+";
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 35px;
  display: flex;
  justify-content: center;
  align-items: center;
}

#dataForm:deep(.tipInfo) {
  color: green !important;
}

#dataForm:deep(.tipError) {
  border: solid 2px red !important;
}

#dataForm:deep(.relData) {
  background: #e6a23c;
}
</style>
